﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleConfigurator.Database;
using VehicleConfigurator.Model;
using VehicleConfigurator.NetUtils;
using log4net;
using VehicleConfigurator.NetUtils.Database;


namespace VehicleConfigurator
{

    public partial class FrmCountryCode : Form
    {
        static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Constructing log
        DataTable dtVat = null;
        public FrmCountryCode()
        {
            InitializeComponent();
            
        }
        private void LoadComponent()
        {
             dtVat = new DataTable();
            dtVat = DBAccess.GetVat();
            // get combobox datagrid column
            var comboBox = this.dgvCountryCode.Columns[FieldNames.VAT_DEFAULT] as DataGridViewComboBoxColumn;
            comboBox.DataSource = dtVat;
            if (dtVat != null)
            {
                if (dtVat.Rows.Count > 0)
                {
                   
                    comboBox.ValueMember = FieldNames.OID;
                    comboBox.DisplayMember = FieldNames.NAME;
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmCountryCode_Load(object sender, EventArgs e)
        {
            this.LoadComponent();
            this.LoadCountryCode();
            this.ReFormatGrid();
        }
        private void LoadCountryCode()
        {
            this.LoadData();
        }


        void ReFormatGrid()
        {
            dgvCountryCode.AllowUserToAddRows = false;
            dgvCountryCode.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvCountryCode.ScrollBars = ScrollBars.Both;
        }

        private CountryCode GetCountryFromRow(DataRow r)
        {
            CountryCode c = new CountryCode();

            c.OID = (int)r[FieldNames.COUNTRY_OID];
            c.Name = r[FieldNames.COUNTRY_NAME].ToString();
            c.Code = r[FieldNames.COUNTRY_CODE].ToString();
            c.IsDefault = r[FieldNames.COUNTRY_IS_DEFAULT].ToString() == "1" ? true : false;
            c.VatDefault = (r[FieldNames.VAT_DEFAULT] == null || r[FieldNames.VAT_DEFAULT] is System.DBNull) ? -1 : (int)r[FieldNames.VAT_DEFAULT];

            return c;
        }


        private void btnNew_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = (DataTable)dgvCountryCode.DataSource;
                CountryCode cc = new CountryCode(-1);
                //row.Cells[col.Name].Value = (row.Cells[col.Name] as DataGridViewComboBoxCell).Items[0];
                
                var dataRow = dt.Rows.Add(cc.OID, cc.Code, cc.Name, cc.IsDefault);
              //  dtVat = null;
                if (dtVat != null && dtVat.Rows.Count > 0)
                {
                    dataRow[FieldNames.VAT_DEFAULT] = dtVat.Rows[0][FieldNames.VAT_OID] ;
                }

                dgvCountryCode.DataSource = dt;
                
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                log.Error(ex.Message);
                throw ex;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = new DataTable();
                dt = (DataTable)dgvCountryCode.DataSource;
                this.UpdateData(dt);
            }
            catch (Exception ex)
            {
                //log.Error(ex.Message);

                //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // throw ex;
                MessageBox.Show("Please check input: " + ex.Message);
            }
        }



        private void dgvCountryCode_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvCountryCode_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show(dgvCountryCode.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            if (dgvCountryCode.Columns[e.ColumnIndex].Name == "isDefault"
                && dgvCountryCode.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "1")
            {
                //MessageBox.Show(dgvCountryCode.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
                foreach (DataGridViewRow r in dgvCountryCode.Rows)
                {
                    if (r.Cells["isDefault"].Value.ToString().Equals("1") && r.Index != e.RowIndex)
                    {
                        r.Cells["isDefault"].Value = false;
                    }
                }
            }
        }

        private void dgvCountryCode_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dgvCountryCode.IsCurrentRowDirty)
                //MessageBox.Show("Value Change" + e.ToString());
                dgvCountryCode.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dgvCountryCode_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {

        }

        private void dgvCountryCode_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow item in this.dgvCountryCode.SelectedRows)
            {
                dgvCountryCode.Rows.RemoveAt(item.Index);

            }
        }


        private void UpdateData1()
        {
            clsDb db = new clsDb();

            db.updateData("country", this.dgvCountryCode);
            this.LoadData();
        }


        private void UpdateData(DataTable dt)
        {
            //add new
            var added = dt.GetChanges(DataRowState.Added);
            if (added != null && added.Rows.Count > 0)
            {
                List<CountryCode> la = new List<CountryCode>();
                foreach (var item in added.Rows)
                {
                    var r = item as DataRow;
                    var v = GetCountryFromRow(r);
                    la.Add(v);
                }
                DBAccess.CreateBulkCountry(la);
            }
            //update
            var updated = dt.GetChanges(DataRowState.Modified);
            if (updated != null && updated.Rows.Count > 0)
            {
                //List<Vat> la = new List<Vat>();
                foreach (var item in updated.Rows)
                {
                    var r = item as DataRow;
                    var v = GetCountryFromRow(r);
                    // la.Add(v);
                    DBAccess.UpdateCountry(v);
                }

            }
            //delete
            var deleted = dt.GetChanges(DataRowState.Deleted);
            var ids1 = Utils.getIdDelete(deleted, FieldNames.OID);
            DBAccess.DeleteByOid(FieldNames.Table.COUNTRY, ids1);
            dt.AcceptChanges();
        }

        public void LoadData()
        {
            //string sql = " SELECT oid,code,name, CASE IsDefault WHEN 1 THEN  TRUE	WHEN 0 THEN FALSE END AS IsDefault FROM country";
            //clsDb db = new clsDb();
            //db.LoadData(sql, dgvCountryCode);

            DataTable dt = new DataTable();
            dt = DBAccess.GetAllCountry();
            this.dgvCountryCode.DataSource = dt;

        }



    }
}
